﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using WAD.WEB.AppCode;
using WAD.Model;
using WAD.DAL;
using System.Text;
using System.Drawing;
using System.Net;
using GL.Tools;
using NSoup.Nodes;
using NSoup;
using NSoup.Select;
using Newtonsoft.Json.Linq;
using GlTool.GlHttp;
using System.Text.RegularExpressions;
using QD.Utils;
using WAD.WEB.AppCode.Html;
using static System.String;

namespace WAD.WEB.Client2.Ajax
{
    /// <summary>
    /// Article 的摘要说明
    /// </summary>
    public partial class HttpSource : AjaxBase
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "getsource": this.GetSource(); break;
                case "getrawurl": this.GetRawUrl(); break;
                case "geteditinfo": this.GetEditInfo(); break;
                case "getvideo": this.GetVideo(); break;
                case "getifengvideo": this.GetIFengVideo(); break;
                case "getvideocomment": this.GetVideoComment(); break;
                case "getyoukuvideo": this.GetYouKuVideo(); break;
                case "gettencentvideo": this.GetTencentVideo(); break;
                case "getqqvideo": this.GetQQVideo(); break;
                case "getqqnewvideo": this.GetQQNewVideo(); break;
                case "getwxvideo": this.GetWxVideo(); break;
                case "getmpvideo": this.GetMpVideo(); break;
                case "getwbvideo": this.GetWbVideo(); break;
                case "getttvideoinfo": this.GetTTVideoInfo(); break;
                case "getttvideo": this.GetTTVideo(); break;
                case "getiqyvideo": this.GetIQYVideo(); break;
            }
        }
        private String url;
        protected override void PageLoad()
        {
            base.PageLoad();
            this.url = Parse.String("url");
        }
        
        /// <summary>
        /// 获取源码
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetSource()
        {
            if (IsNullOrEmpty(url)) ParamError();

            string isInfo = Parse.String("isinfo", ""); //0 只返回源码, 1 返回多个参数 如： id,source
            if (isInfo.Equals("1"))
            {
                var model = HttpTool.GetSavaSource(url, true, true);
                if(model!=null)
                Success(model);
                else
                {
                    Fail("不支持的链接地址");
                }
            }
            else
            {
                String html = HttpTool.GetAndSavaSource(url, false, true);
                if (!IsNullOrEmpty(html))
                    Success(html);
            }
            Fail();
        }
        /// <summary>
        /// 获取重定向后的Url
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetRawUrl()
        {
           
            if (IsNullOrEmpty(url)) ParamError();
            var uri = new Uri(url);
            QD.Utils.WebHttpHelper.UserAgent =HttpTool.MOBILE_USER_AGENT;
            var returnUrl = Empty;
            var html=WebHttpHelper.Request(url, "", "GET", Encoding.UTF8, out returnUrl);
            if (uri.Host.Equals("news.qq.com", StringComparison.OrdinalIgnoreCase))
            {
                html = WebHttpHelper.Request(url, "", "GET", Encoding.GetEncoding("GB2312"), out returnUrl);
                Regex r1 = new Regex("[a-zA-z]+://xw.qq.com/[^\\s]*\"");

                if (r1.IsMatch(html))
                {
                    var u = r1.Match(html).Groups[0].Value.TrimEnd('\"');
                    returnUrl = u;

                }
            }
            var returnUri=new Uri(returnUrl);
            if (returnUri.Host.Equals("m.365yg.com", StringComparison.OrdinalIgnoreCase))
            {
                Fail("该地址已启用防盗链");
            }else if (returnUri.Host.Equals("play.v.qq.com", StringComparison.OrdinalIgnoreCase))
            {
                Fail("该地址已启用防盗链");
            }
            Success(returnUrl);

        }

        /// <summary>
        /// 获取编辑Url时需要的数据
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetEditInfo()
        {
            if (IsNullOrEmpty(url))
            {
                ParamError();
            }
            //String html = HttpTool.GetAndSavaSource(url, false, false);       //2016-08-02注释,不支持url.cn链接

            Dictionary<string, object> model = HttpTool.GetSavaSource(url, false, false);

            string html = Convert.ToString(model["source"]);
            
            if (url.IndexOf("url.cn") > -1)
                url = Convert.ToString(model["return_url"]);    //url.cn重定向后的域名
            
            // 解析一个HTML字符串
            Document doc = NSoupClient.Parse(html);
            List<String> imgList = new List<String>();
            
            
            String title = doc.Title;   //标题
            if (url.IndexOf("://view.inews.qq.com") > -1)
            {
                //解决标题显示“腾讯新闻”问题
                Regex r1 = new Regex("<p class=\"title\" align=\"left\">([\\s\\S].*?)</p>");
                if (r1.IsMatch(html))
                    title = r1.Match(html).Groups[1].Value;

                //内容图片2017-11-06
                Regex rImg = new Regex("\"imgurl641\":{\"imgurl\":\"([\\s\\S].*?)\"");
                if (rImg.IsMatch(html))
                {
                    foreach (Match match in rImg.Matches(html))
                    {
                        if (imgList.Count > 7) break;
                        imgList.Add(match.Groups[1].Value.Replace("\\/", "/")); //内容图片
                    }
                }
            }
            
            if (url.IndexOf("://mp.weixin.qq.com/") != -1)
            {
                String wxArticleInfoTxt = GetWxInfoTxt(doc);

                // 取获取订阅号的logo
                String wxLogo = GetWxTitleLogo(wxArticleInfoTxt);
                if (wxLogo != null && wxLogo.StartsWith("http"))
                {
                    wxLogo = ConfigurationManager.AppSettings["proxyimg"] + wxLogo;
                    imgList.Add(wxLogo);
                }              
            }

            // 匹配内容的图片
            Elements imgs = doc.Select("img");
            foreach (Element e in imgs)
            {
                // 只取前8条记录
                if (imgList.Count > 7)
                {
                    break;
                }

                // 微信订阅号文章的图片使用data-src
                String src = url.IndexOf("://mp.weixin.qq.com/") != -1 ? e.Attr("data-src") : e.Attr("src");

                //图片链接太长 2017-11-06
                if (src.IndexOf("data:image/") > -1) continue;

                // 过滤gif动画并且长度至少大于10
                if (src.Length > 10 && src.IndexOf("wx_fmt=gif") == -1)
                {
                    if (url.IndexOf("toutiao.com") > -1)
                    {
                        if (src.IndexOf("http://") == -1)
                        {
                            if (src.IndexOf("//") == 0)
                                src = "http:" + src;
                            else
                                src = "http://" + src;
                        }
                    }
                    if (url.IndexOf("://mp.weixin.qq.com/", StringComparison.OrdinalIgnoreCase) != -1)
                        src = ConfigurationManager.AppSettings["proxyimg"] + src;
                        // 不添加重复的图片
                        if (!imgList.Contains(src))
                    {
                        imgList.Add(src);
                    }
                }
            }

            Dictionary<String, Object> data = new Dictionary<String, Object>();
            data.Add("title", title);
            data.Add("imgList", imgList);
            //data.Add("desc", desc);

            html = null;
            
            Success(data);
        }

        #region 获取视频
        /// <summary>
        /// 获取网络视频地址
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetVideo()
        {
            if (IsNullOrEmpty(url)) ParamError();
            var uri=new Uri(url);
            if (url.IndexOf("v.qq.com/") != -1)
                GetQQVideo();       // 腾讯视频
            else if (url.IndexOf("view.inews.qq.com/") != -1)
                GetQQNewVideo();    //腾讯新闻视频
            else if (url.IndexOf("v.youku.com/") != -1)
                GetYouKuVideo();    // 优酷视频
            else if (url.IndexOf("mp.weixin.qq.com/") != -1)
                GetWxVideo();       // 微信视频
            else if (url.IndexOf("m.weibo.cn/") != -1)
                GetWbVideo();       // 微博视频
            else if (url.IndexOf("toutiao.com/") != -1)
                GetTTVideoInfo();   // 今日头条视频
            else if (url.IndexOf("www.meipai.com/") != -1)
                GetMpVideo();       // 美拍视频
            else if (url.IndexOf("tv.sohu.com/") != -1)
                GetSohuVideo();     //搜狐视频
            else if (url.IndexOf("iqiyi.com/") != -1)
                GetIQYVideo();     //爱奇异视频
            else if (uri.Host.Equals("v.ifeng.com", StringComparison.OrdinalIgnoreCase))
                GetIFengVideo();
            else
                GetVideoComment();
        }
        /// <summary>
        /// 获取凤凰视频
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void GetIFengVideo()
        {
            if (IsNullOrEmpty(url))
            {
                ParamError();
            }
            var uri=new Uri(url);
            var path=uri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
            var vc = path.Split('/').Last().Replace(".shtml", "");
            var murl = $"http://dyn.v.ifeng.com/cmpp/video_msg_ipad.js?msg={vc}";
            var json = HttpTool.GetHttpString(murl, true);
            var reg=new Regex("[a-zA-z]+://[^\\s]*.mp4");
            if (!reg.IsMatch(json)) JsonResult(11, "未找到视频");
            var src= reg.Match(json).Groups[0].Value;
            Success(src);
        }

        //获取url中的html源码里的video视频 支持像内涵段子这样的app视频
        [QD.Web.Ajax.AjaxMethod]
        public void GetVideoComment()
        {
            if (IsNullOrEmpty(url))
            {
                ParamError();
            }

            // 手机端源码
            String html = HttpTool.GetHttpString(url, true);

            // 解析一个HTML字符串
            Document doc = NSoupClient.Parse(html);
            Elements eles = doc.Select("video");
            if (eles.IsEmpty)
            {

                // PC端源码
                html = HttpTool.GetHttpString(url);
                doc = NSoupClient.Parse(html);
                eles = doc.Select("video");
            }

            if (eles.IsEmpty)
            {
                JsonResult(11, "未找到视频");
                //Fail();
            }

            Element ele = eles.First;

            // 得到视频播放的url
            String src = ele.Attr("src");
            String thumb = ele.Attr("poster");

            Dictionary<String, String> map = new Dictionary<string, string>();
            map.Add("src", src);
            map.Add("thumb", thumb);
            Success(map);
        }

        //获取优酷视频
        [QD.Web.Ajax.AjaxMethod]
        public void GetYouKuVideo()
        {
            if (IsNullOrEmpty(url))
            {
                ParamError();
            }

            // 优酷视频去掉参数为电脑版源代码,这样才能得到视频代码
            if (url.IndexOf("?") != -1)
            {
                url = url.Substring(0, url.IndexOf("?"));
            }
            String html = HttpTool.GetHttpString(url);

            // 解析一个HTML字符串
            Document doc = NSoupClient.Parse(html);
            Element ele = doc.Select("#link4").First();
            if (ele == null)
            {
                Fail();
            }

            //2016-09-23注释
            //String iframe = ele.Val();
            //String cpF = iframe;
            //cpF = cpF.Substring(cpF.IndexOf("src=\"") + 5);
            //// 得到视频播放的url
            //String src = cpF.Substring(0, cpF.IndexOf("\""));


            Regex r1 = new Regex("src='([\\s\\S].*?)'");
            string src = r1.Match(ele.OuterHtml()).Groups[1].Value;
            if (IsNullOrEmpty(src))
                JsonResult(11, "未找到视频");

            Success(src);
        }

        //获取腾讯视频
        [QD.Web.Ajax.AjaxMethod]
        public void GetTencentVideo()
        {
            String vid = Parse.String("vid");
            if (IsNullOrEmpty(vid))
            {
                ParamError();
            }

            // 读取腾讯视频地址的url
            String jsonUrl = "http://vv.video.qq.com/geturl?vid=" + vid + "&otype=json&platform=1&ran=0%2E9652906153351068";
            String html = HttpTool.GetHttpString(jsonUrl);

            JObject jo = JObject.Parse(html.Substring("QZOutputJson=".Length, html.Length - "QZOutputJson=".Length - 1));
            //String src = ((JObject)((JArray)((JObject)jo["vd"])["vi"])[0])["url"].ToString();

            String src = jo["vd"]["vi"][0]["url"].ToString();
            Success(src);
        }

        //获取腾讯视频
        [QD.Web.Ajax.AjaxMethod]
        public void GetQQVideo()
        {
            if (IsNullOrEmpty(url))
                ParamError();

            String vid = null;  // 视频id
            if (url.IndexOf("vid=") > -1)
            {
                String cpUrl = url;
                cpUrl = cpUrl.Substring(cpUrl.IndexOf("vid=") + 4);

                if (cpUrl.IndexOf("&") != -1)
                    vid = cpUrl.Substring(0, cpUrl.IndexOf("&"));
                else
                    vid = cpUrl;
            }
            else if (url.IndexOf("q/") > -1 && url.IndexOf(".") > -1)
            {
                try
                {
                    int start = url.LastIndexOf("q/") + 2;
                    vid = url.Substring(start, url.IndexOf(".html") - start);
                }
                catch { }

            }
            else if (url.IndexOf("live") > -1)
            {
                //获取源码，正则匹配
                //链接格式：http://v.qq.com/live/p/topic/6309/review.html?&ptag=4_4.8.5.12398_wxf&from=groupmessage&isappinstalled=0
                String html = HttpTool.GetHttpString(url, true);
                Regex r1 = new Regex("vid: \"([\\s\\S].*?)\"");
                if (r1.IsMatch(html))
                {
                    vid = r1.Match(html).Groups[1].Value;
                }
            }
            else if (url.IndexOf("v.qq.com") > -1 || url.IndexOf("m.v.qq.com") > -1)
            {
                //从URL地址中取，如：https://m.v.qq.com/page/l/d/s/l0313o3ftds.html?ptag=v_qq_com%23v.play.adaptor%233
                int start = url.LastIndexOf("/");
                int end = url.IndexOf(".html");
                if (start > -1 && end > -1)
                    vid = url.Substring(start + 1, end - start - 1);
            }
          

            if (!IsNullOrEmpty(vid))
            {
                Dictionary<String, String> map = new Dictionary<string, string>();
                map.Add("vid", vid);
                map.Add("thumb", Format("http://vpic.video.qq.com/74779331/" + vid + "_ori_3.jpg"));
                Success(map);
            }

            Fail();
        }

        //腾讯新闻视频
        [QD.Web.Ajax.AjaxMethod]
        public void GetQQNewVideo()
        {
            if (IsNullOrEmpty(url))
            {
                ParamError();
            }
            String html = HttpTool.GetHttpString(url, true);

            // 解析一个HTML字符串
            Document doc = NSoupClient.Parse(html);
            Element ele = doc.Select("div[vid]").First();
            if (ele == null)
            {
                Fail();
            }

            // 得到腾讯视频的id
            String vid = ele.Attr("vid");

            // 视频缩略图
            String thumb = "http://vpic.video.qq.com/74779331/" + vid + "_ori_3.jpg";

            Dictionary<String, String> map = new Dictionary<string, string>();
            map.Add("vid", vid);
            map.Add("thumb", thumb);
            Success(map);
        }

        //微信视频
        [QD.Web.Ajax.AjaxMethod]
        public void GetWxVideo()
        {
            if (IsNullOrEmpty(url))
                ParamError();
            String html = HttpTool.GetHttpString(url);

            // 解析一个HTML字符串
            Document doc = NSoupClient.Parse(html);
            Elements items = doc.Select(".video_iframe");
            if (items == null || items.Count < 1)
                JsonResult(11, "未找到视频");

            String cpUrl = items.First().Attr("data-src");
            if (cpUrl.Length > 0)
            {
                cpUrl = cpUrl.Substring(cpUrl.IndexOf("vid=") + 4);

                String vid = "";     // 视频id
                if (cpUrl.IndexOf("&") != -1)
                    vid = cpUrl.Substring(0, cpUrl.IndexOf("&"));
                else
                    vid = cpUrl;
                String vid2 = vid;

                // 视频缩略图
                String thumb = "http://vpic.video.qq.com/74779331/" + vid + "_ori_3.jpg";
                Dictionary<String, String> map = new Dictionary<string, string>();
                map.Add("vid", vid2);
                map.Add("thumb", thumb);
                Success(map);
            }
            else
            {
                //通过正则匹配
                string vedio_html = items.First().OuterHtml();
                Regex r1 = new Regex("vid=([\\s\\S].*?)\"");
                if (r1.IsMatch(vedio_html))
                {
                    // 视频id
                    string vid = r1.Match(vedio_html).Groups[1].Value;
                    Dictionary<String, String> map = new Dictionary<string, string>();
                    map.Add("vid", vid);
                    map.Add("thumb", "http://vpic.video.qq.com/74779331/" + vid + "_ori_3.jpg");
                    Success(map);
                }
            }
            JsonResult(11, "未找到视频");
        }

        //美拍视频
        [QD.Web.Ajax.AjaxMethod]
        public void GetMpVideo()
        {
            String html = HttpTool.GetHttpString(url);

            // 解析一个HTML字符串
            Document doc = NSoupClient.Parse(html);
            Element ele = doc.Select("#detailVideo").First();

            //得到视频地址
            String src = ele.Attr("data-video");

            //得到缩略图
            String thumb = ele.Child(0).Attr("src");

            Dictionary<String, String> map = new Dictionary<string, string>();
            map.Add("src", src);
            map.Add("thumb", thumb);
            Success(map);
        }

        //微博视频
        [QD.Web.Ajax.AjaxMethod]
        public void GetWbVideo()
        {
            if (IsNullOrEmpty(url))
            {
                ParamError();
            }
            GlHttpGet httpGet = new GlHttpGet(url);

            // 微博登录cookie值
            httpGet.setCookie("SUB",
                    "_2A257mMopDeRxGeNI7lYX8ynEyjWIHXVZYtZhrDV6PUJbrdBeLU7hkW1LHesYdMzPhokz4ieQAEkvHIv2YDFlKg");
            GlHttpResponse resp = null;
            try
            {
                resp = httpGet.Execute();

                // 得到源码
                String html = resp.ToHtml();
                String cpHtml = html;

                String tag = "window.$render_data = ";
                cpHtml = cpHtml.Substring(cpHtml.IndexOf(tag) + tag.Length);
                cpHtml = cpHtml.Substring(0, cpHtml.IndexOf(";</script>")).Replace("'", "\"");

                JObject jo = JObject.Parse(cpHtml);

                JToken pageInfo = jo["stage"]["single"][1]["mblog"]["page_info"];

                // 缩略图
                String thumb = pageInfo["pic_info"]["pic_middle"]["url"].ToString();

                // 得到视频地址
                String src = pageInfo["media_info"]["mp4_hd_url"].ToString();

                Dictionary<String, String> map = new Dictionary<string, string>();
                map.Add("src", src);
                map.Add("thumb", thumb);
                Success(map);

            }
            finally
            {
                try
                {
                    resp.Close();
                }
                catch
                {
                }
            }
        }

        //搜狐视频
        private void GetSohuVideo()
        {
            String html = HttpTool.GetHttpString(url);
            Regex r1 = new Regex("og:videosrc\" content=\"([\\s\\S].*?)\" />");
            if (!r1.IsMatch(html))
                JsonResult(11, "未找到视频");

            Success(r1.Match(html).Groups[1].Value);
        }

        //获得头条视频信息
        [QD.Web.Ajax.AjaxMethod]
        public void GetTTVideoInfo()
        {
            if (IsNullOrEmpty(url))
            {
                ParamError();
            }
            String html = HttpTool.GetHttpString(url);

            // 解析一个HTML字符串
            Document doc = NSoupClient.Parse(html);

            Elements els=doc.Select("div[tt-videoid]");
            if (els == null || IsNullOrEmpty(els.Html()))
                JsonResult(11, "未找到视频");

            Element ele = els.First();
            // 得到今日头条的视频id
            String videoid = ele.Attr("tt-videoid");

            // 缩略图
            String thumb = ele.Attr("tt-poster");

            Dictionary<String, String> map = new Dictionary<string, string>();
            map.Add("videoid", videoid);
            map.Add("thumb", thumb);
            Success(map);
        }
        
        //获得头条视频地址
        [QD.Web.Ajax.AjaxMethod]
        public void GetTTVideo()
        {

            // 得到今日头条的视频id
            String videoid = Parse.String("videoid");

            // 拼接url
            String jsonUrl = "http://i.snssdk.com/video/urls/1/toutiao/mp4/" + videoid;
            String jStr = HttpTool.GetHttpString(jsonUrl);

            if (jStr == null)
            {
                Fail();
            }

            JObject jo = JObject.Parse(jStr);

            // 得到被编码的视频url
            String decodeUrl = jo["data"]["video_list"]["video_1"]["main_url"].ToString();

            // 解码视频地址
            String src = StringHelper.BASE64Decoder(decodeUrl);
            Success(src);
        }

        //爱奇艺视频处理
        [QD.Web.Ajax.AjaxMethod]
        public void GetIQYVideo()
        {
            if (IsNullOrEmpty(url))
            {
                ParamError();
            }

            // 手机端源码
            String html = HttpTool.GetHttpString(url, false);

            Regex r1 = new Regex("data-player-videoid=\"([\\s\\S].*?)\"");
            Regex r2 = new Regex("data-player-tvid=\"([\\s\\S].*?)\"");
            //Regex r3 = new Regex("property=\"og:image\" content=\"([\\s\\S].*?)\"");
            //Regex r4 = new Regex("iqiyi.com/([\\s\\S].*?).html");


            string videoid = r1.Match(html).Groups[1].Value;
            string tvid = r2.Match(html).Groups[1].Value;
            //string thumb = r3.Match(html).Groups[1].Value;
            //string name = r4.Match(url).Groups[1].Value;

            if (videoid.Equals("") || tvid.Equals(""))
                JsonResult(11, "未找到视频");

            // 得到视频播放的url
            //string src = string.Format("http://player.video.qiyi.com/{0}/0/0/{1}-albumId=6035108009-tvId={2}-isPurchase=0-cnId=5", videoid, name, tvid);
            string src = Format("http://open.iqiyi.com/developer/player_js/coopPlayerIndex.html?vid={0}&tvId={1}", videoid, tvid);

            Success(src);
        }
        #endregion

        //获取订阅号文章logo
        private String GetWxInfoTxt(Document doc)
        {
            try
            {

                // 如果是订阅号 取logo
                Elements scripts = doc.Select("script");
                String txt = null;

                // 倒序速度比较快 因为存放logo的script可能在最后
                for (int i = scripts.Count - 1; i >= 0; i--)
                {
                    txt = scripts[i].Html();
                    if (txt.IndexOf("msg_cdn_url") != -1)
                    {
                        return txt;
                    }
                }
                return null;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        //获取订阅号标题logo
        private String GetWxTitleLogo(String script)
        {
            try
            {
                String wxLogo = script.Substring(script.IndexOf("msg_cdn_url"), script.IndexOf("msg_link") - script.IndexOf("msg_cdn_url"));
                return wxLogo.Substring(wxLogo.IndexOf("\"") + 1, wxLogo.LastIndexOf("\"") - wxLogo.IndexOf("\"") - 1);
            }
            catch (Exception e)
            {
                return null;
            }
        }

        //获取订阅号文章简介
        private String GetWxDesc(String script)
        {
            try
            {
                String wxDesc = script.Substring(script.IndexOf("msg_desc"), script.IndexOf("msg_cdn_url") - script.IndexOf("msg_desc"));
                return wxDesc.Substring(wxDesc.IndexOf("\"") + 1, wxDesc.LastIndexOf("\"") - wxDesc.IndexOf("\"") - 1);
            }
            catch (Exception e)
            {
                return null;
            }
        }

    }
}